package fdoj.eventInvitations.servlet;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.util.HashMap;
import java.util.List;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.gdata.client.contacts.*;
import com.google.gdata.client.http.*;
import com.google.gdata.data.contacts.ContactEntry;
import com.google.gdata.data.contacts.ContactFeed;
import com.google.gdata.data.extensions.Email;
import com.google.gdata.data.extensions.Name;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;

import fdoj.eventInvitations.dao.PersonDao;
import fdoj.eventInvitations.entity.Contact;
import fdoj.eventInvitations.entity.Person;

public class GoogleContactsApi extends HttpServlet {

	@EJB
	PersonDao personDao;

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	public String convert(String s) {
		s.toLowerCase();
		s = s.replace("č", "c");
		s = s.replace("ć", "c");
		s = s.replace("ž", "z");
		s = s.replace("đ", "dj");
		s = s.replace("š", "s");
		return s;
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			HttpSession session = request.getSession();
			if (session != null) {
				Person loggedUser = null;
				if ((loggedUser = (Person) session.getAttribute("loggedUser")) != null) {
					String token = null;
					if ((token = request.getParameter("token")) == null) {
						getToken(response);
						return;
					}
					ContactFeed resultFeed = getContacts(token);
					HashMap<Integer,Contact> googleContacts=getContactsFromFeed(resultFeed);
					session.setAttribute("importContacts", googleContacts);
					request.getRequestDispatcher("./importGoogleContacts.jsp")
							.forward(request, response);
					return;
				}
				else{
					response.sendRedirect(response.encodeRedirectURL("./index"));
					return;
				}
			}
			response.sendRedirect(response.encodeRedirectURL("./index"));
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private HashMap<Integer, Contact> getContactsFromFeed(ContactFeed resultFeed) {
		HashMap<Integer, Contact> googleContacts = new HashMap<Integer, Contact>();
		Integer i = 0;
		for (ContactEntry entry : resultFeed.getEntries()) {
			List<Email> emails = entry.getEmailAddresses();
			if (!emails.isEmpty()) {
				String email = emails.get(0).getAddress();
				String fullname = null;
				if (entry.hasName()) {
					Name name = entry.getName();
					if (name.hasFullName()) {
						fullname = name.getFullName().getValue();
					}
				}
				Contact c = new Contact();
				c.setValid(true);
				c.setEmail(email);
				String firstName = null;
				String lastName = null;
				if (fullname != null) {
					String[] names = fullname.split(" ");
					if (names.length >= 2) {
						lastName = names[1];
						firstName = names[0];

					} else if (names.length >= 1) {
						firstName = names[0];
					}
				}
				if (firstName != null) {
					firstName = convert(firstName);
				}
				c.setFirstName(firstName);
				if (lastName != null) {
					lastName = convert(lastName);
				}
				c.setLastName(lastName);
				c.setId(i++);
				googleContacts.put(c.getId(), c);
			}
		}
		return googleContacts;
	}

	private ContactFeed getContacts(String token) {
		String feedUrl = "https://www.google.com/m8/feeds/contacts/default/full";
		String sessionToken = null;
		ContactFeed resultFeed = null;
		try {
			sessionToken = AuthSubUtil.exchangeForSessionToken(token, null);

			ContactsService myService = new ContactsService("fdoj-poziv-0.01");
			myService.setAuthSubToken(sessionToken, null);
			URL url = new URL(feedUrl);
			resultFeed = myService.getFeed(url, ContactFeed.class);
		} catch (AuthenticationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (GeneralSecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ServiceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return resultFeed;
	}

	private void getToken(HttpServletResponse response) {
		String next = "http://localhost:8080/PozivNaDogadjaj/googlecontactsapi";
		String scope = "https://www.google.com/m8/feeds/";
		boolean secure = false;
		boolean sess = true;
		String authSubLogin = AuthSubUtil.getRequestUrl(next, scope, secure,
				sess);
		System.out.println(authSubLogin);
		try {
			response.sendRedirect(response.encodeRedirectURL(authSubLogin));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return;
	}
}
